package com.zenghus.view.proxy;

import com.zenghus.proxy.Menthod;
import com.zenghus.view.proxy.annotation.EventView;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ObjectProxy implements MethodInterceptor {

    private Object obj;

    private Object callback;//回调对象

    ObjectProxy(Object objs) {
        this.obj = objs;
    }

    public Object newProxyInstance(Object callback) {
        this.callback=callback;
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(obj.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object ob = methodProxy.invokeSuper(o,objects);
        if(callback!=null){
            String methodname=method.getName();
            Class cb=callback.getClass();
            //获取回调对象的方法
            Method[] m=cb.getMethods();
            //循环获取方法与目标方法是否一致
            for (int i = 0; i < m.length; i++) {
                EventView ev= m[i].getAnnotation(EventView.class);
                if(ev!=null && ev.originalMethod().equals(methodname)){
                    m[i].invoke(callback,null);
                    break;
                }
            }
        }
        return ob;
    }
}

